import { getSetting,chooseAddress,openSetting } from '../../utils/asyncWx.js'
Page({
  data: {
    address:{},
    cart:[],
    allChecked: false,
    // 总价格
    total_price :0,
    // 总数量
    total_quantity : 0
  },
  onShow: function() {
    const address = wx.getStorageSync('address')
    // 获取缓存中的收货地址信息
     const cart = wx.getStorageSync('cart') || []
     this.setData({
      address
     })
     this.setCart(cart)
  },
  // 点击收货地址
  async handleChooseAddress() {
    try {
      
      const res1 = await getSetting()
      const scopeAddress = res1.authSetting['scope.address']
      if(scopeAddress === false) {
         await openSetting()
      }
      // 调用获取收货地址的API
      const address = await chooseAddress()
      // 存入到缓存
      wx.setStorageSync('address', address)
    }
  catch(error) {
    console.log(error)
  }
},
handeItemChange(e) {
  // 获取被修改的商品ID
  const goods_id = e.currentTarget.dataset.id
  console.log(goods_id)
  // 获取购物车数组
  let cart = this.data.cart
  console.log(cart)
  // 找到被修改的商品对象
  let index = cart.findIndex(v =>
    v.goods_id === goods_id
    )
  // 选中状态取反
  console.log(index)
  console.log(cart[index])
  cart[index].checked =!cart[index].checked
  // 吧购物车数据重新设置回data中和缓存中
  this.setCart(cart)
},
setCart(cart) {
  // const allChecked =cart.length > 0 ? cart.every(v =>v.checked) : false
  //    let total_price = 0
  //    let total_quantity = 0
  //    if(cart.length > 0) {
  //      cart.forEach(v => {
  //       total_price += v.num * v.goods_price
  //       total_quantity += v.num
  //      })
  //    }
  //    this.setData({
  //     cart,
  //     total_price,
  //     total_quantity,
  //     allChecked
  //   })
  //  wx.setStorageSync('cart', cart)
   
   let allChecked = true;
   // 1 总价格 总数量
   let total_price = 0;
   let total_quantity = 0;
   cart.forEach(v => {
     if (v.checked) {
       total_price += v.num * v.goods_price;
       total_quantity += v.num;
     } else {
       allChecked = false;
     }
   })
   // 判断数组是否为空
   allChecked = cart.length != 0 ? allChecked : false;
   this.setData({
     cart,
     total_price, total_quantity, allChecked
   });
   wx.setStorageSync("cart", cart);
},
handleItemAllChenck() {
   let {cart,allChecked} = this.data
   console.log(cart,allChecked)
   allChecked =!allChecked
   cart.forEach(v => v.checked =allChecked)
   this.setCart(cart)
 },
 handleItemNumEdit(e) {
   console.log(e)
   let id = e.currentTarget.dataset.id
   let {cart} = this.data
   let index = cart.findIndex(v => {
     return v.goods_id = id
   })
  cart[index].num += e.currentTarget.dataset.operation
  this.setCart(cart)
 }
})